package cn.yr.clock.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.yr.common.exception.ret.Ret;
import cn.yr.oss.OssKit;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private OssKit ossKit;

    @RequestMapping("/upload")
    public Ret upload(MultipartFile file){
        long maxSize = 10*1024*1024;
        if(file.getSize()>maxSize){
            return Ret.error("文件不能大于10M");
        }
        try {
            if(StrUtil.isEmpty(file.getOriginalFilename())){
                return Ret.error("文件名不能为空");
            }
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            Snowflake snowflake = IdUtil.getSnowflake();
            long id = snowflake.nextId();
            String imgName = id+suffix;
            String upload = ossKit.upload(file.getBytes(), imgName);
            return Ret.success(MapUtil.builder("img",upload).map());
        }catch (Exception e){
            return Ret.error(e.getMessage());
        }
    }

}
